// -----------------------------------------------------------------------
//  <copyright file="OrSpecification.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2024 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2024/12/23 14:08</last-date>
// -----------------------------------------------------------------------

using DaprPlus.Domain.Entity;


namespace DaprPlus.Specifications;

/// <summary>
/// Or组合规范，该规范表明给定对象应满足给定规范中其中之一。
/// </summary>
/// <typeparam name="T"></typeparam>
public class OrSpecification<T> : SpecificationBase<T> where T : IEntity
{
    public OrSpecification(ISpecification<T> left, ISpecification<T> right)
        : base(left.Criteria.Or(right.Criteria))
    {
        foreach (var item in left.Includes.Union(right.Includes))
        {
            AddInclude(item);
        }

        foreach (var item in left.IncludeStrings.Union(right.IncludeStrings).Distinct())
        {
            AddInclude(item);
        }

        foreach (var item in left.OrderExpressions.Union(right.OrderExpressions))
        {
            AddOrderBy(item.OrderByExpression, item.IsDescending);
        }

        foreach (var item in left.OrderStrings.Union(right.OrderStrings).Distinct())
        {
            AddOrderBy(item.FieldName, item.IsDescending);
        }

        // 处理分页信息 - 优先使用左侧规约的分页设置
        if (left.IsPagingEnabled)
        {
            ApplyPaging(left.Skip, left.Take);
        }
        else if (right.IsPagingEnabled)
        {
            ApplyPaging(right.Skip, right.Take);
        }
    }
}
